import config from '../config';
import axios from 'axios';
import store from '../store';
import {ElMessage} from 'element-plus'


class HttpRequest{
	public baseURL:string;
	public timeout:number;
	constructor(){
		this.baseURL = config.baseUrl;
		this.timeout = 30000; //30s请求超时
	}
	//请求拦截
	setInterceptors(instance:any){
		//请求
		instance.interceptors.request.use( (config: any) =>{
			config.headers.common['Accept'] = 'application/json';
			config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
			//获取sessionsId 没有就调整登录页
			return config
		}, (error: any) =>{
			return Promise.reject(error)
		});
		//响应
		instance.interceptors.response.use((res:any)=>{
			if(res.status.indexOf('20')>-1){
				return Promise.resolve(res.data)
			}else{
				return Promise.reject(res.data)
			}
		},(error:any)=>{
			//超时
			if(error && error.stack.indexOf('timeout')>-1){
				ElMessage('当前网络信号差，请稍后再试。')
			}
			//
			switch(error.response.status){
				case 400: 
					error.response = error.response.data
					break;
				case 403:
					error.response = error.response.data
					break;
				case 404:
					ElMessage('请求错误，未找到该资源。')
					break;
				case 500:
					error.response = error.response.data
					break;
				default:
					break;
			}

		})
	}
	mergeOptions(options:any){
		this.baseURL = config.baseUrl;
		return {baseURL: this.baseURL,timeout:this.timeout, ...options}
	}
	request(options:any){
		const instance = axios.create();
		this.setInterceptors(instance);
		const opts = this.mergeOptions(options);
		return instance(opts)
	}
	get(url:string, config:any){
		return this.request({
			method: "get",
			url,
			...config
		})
	}
	post(url:string,data: Object, config:any){
		return this.request({
			method: "post",
			url,
			data,
			...config
		})
	}
	put(url:string, data: Object,config:any){
		return this.request({
			method: "put",
			url,
			data,
			...config
		})
	}
	del(url:string,data: Object, config:any){
		return this.request({
			method: "delete",
			url,
			data,
			...config
		})
	}
}
export default new HttpRequest;
